package com.googlecode.studentrecords;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;

/**Interacts with SRDatabase and SRView to perform event-based actions*/
public class SRController{
	
	private SRDatabase model;
	private SRView view;
	
	private JComponent c;
	
	/**SRController is instantiated with local copies 
	 * of SRDatabases and SRView
	 * 
	 * @param newModel
	 * @param newView
	 */
	SRController(SRDatabase newModel, SRView newView)
	{
		model = newModel;
		view = newView;
	
		view.addLoginListener(new LoginListener());
	}
	
	/**LoginListener controls events for the login page
	 *
	 */
	class LoginListener implements ActionListener {
		public void actionPerformed(ActionEvent action) {
			if(action.getSource().equals(view.loginButton)){
				if(view.passwordCheck() == true)
				{
					System.out.println("Logged in!\n");

					c = view.createInformationPane();		
					view.showPane(c);
					
					view.createMenu();
					view.addMenuListener(new MenuListener());
				}
				else{
					System.out.println("Invalid username/password. "
							+ "Please try again.");
				}
			}
		}
	}
	
	/**MenuListener controls events for menu items
	 *
	 */
	class MenuListener implements ActionListener {
		public void actionPerformed(ActionEvent action) {
			if(action.getSource().equals(view.logout)){
				System.out.println("Logged Out.");
				new SRView(model);
			}
			else if(action.getSource().equals(view.quit)) {
				System.out.println("Quit.");
				System.exit(0);
			}
			else if(action.getSource().equals(view.updateInfo)) {
				System.out.println("Update info.");
				c = view.createUpdatePane();
				view.showPane(c);
				view.addUpdateListener(new UpdateListener());
			}
		}
		
	/**UpdateListener controls events for Update window
	 *
	 */
	class UpdateListener implements ActionListener {
		public void actionPerformed(ActionEvent action) {
			if(action.getSource().equals(view.submitButton)){
				
				view.updateFields();
				System.out.println("Updated.");
			}
			else if (action.getSource().equals(view.cancelButton)){
				
				System.out.println("Cancelled.");
				view.showPane(view.informationPane);
			}
		}
	}
}

}
